/**
 * 这个是一个深度优先遍历问题，直接使用递归就可以实现了
遍历每一个元素，如果这个元素没有children属性就直接加入到结果数组中去；如果有children属性，就对children递归，将递归结果加入到结果数组中去，然后删除此元素的children属性，并加入到结果数组中去。

 * @param {*} treeArr 
 * @returns 
 */
function treeConvertToArr(treeArr) {
  const result = [];
  treeArr.forEach((treeObj) => {
    if (treeObj.children) {
      const childrenList = treeObj.children;
      result.push(...treeConvertToArr(childrenList));
      delete treeObj["children"];
    }
    result.push(treeObj);
  });

  return result;
}

// egg:
const source = [
  {
    id: 1,
    pid: 0,
    name: "body",
    children: [
      {
        id: 2,
        pid: 1,
        name: "title",
        children: [
          {
            id: 3,
            pid: 2,
            name: "div",
          },
        ],
      },
    ],
  },
  {
    id: 4,
    pid: 0,
    name: "html",
    children: [
      {
        id: 5,
        pid: 4,
        name: "div",
        children: [
          {
            id: 7,
            pid: 5,
            name: "img",
          },
        ],
      },
    ],
  },
];

console.log(treeConvertToArr(source));
